package wnhz.com.business.rebateshop.activity.home;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import wnhz.com.business.MyApplication;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseRVAdapter;
import wnhz.com.business.base.BaseViewHolder;
import wnhz.com.business.base.MyBaseActivity;
import wnhz.com.business.groupshop.adapter.QuanZiImageAdapter;
import wnhz.com.business.groupshop.bean.ShareInfo;
import wnhz.com.business.groupshop.ui.AllCommentActivity;
import wnhz.com.business.groupshop.ui.StoreActivity;
import wnhz.com.business.impl.ActionBarClickListener;
import wnhz.com.business.netcallback.StringDialogCallback;
import wnhz.com.business.rebateshop.bean.GoodsDetailInfoBean2;
import wnhz.com.business.uitls.LogUtils;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.ToastUtils;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;
import wnhz.com.business.uitls.dialog.ShareDialog;
import wnhz.com.business.view.CircleImageView;
import wnhz.com.business.view.ExpandTextView;
import wnhz.com.business.view.NoScrollGridView;
import wnhz.com.business.view.TranslucentActionBar;

public class RebateGoodsDetailsActivity extends MyBaseActivity implements View.OnClickListener, ActionBarClickListener {
    private static final String TAG = "RebateGoodsDetailsActivity";

    @BindView(R.id.tv_collect)
    TextView tv_collect;
    @BindView(R.id.tv_sales)
    TextView tv_sales;
    @BindView(R.id.ll_allComment)
    LinearLayout ll_allComment;
    @BindView(R.id.tv_comment)
    TextView tv_comment;
    @BindView(R.id.iv_userImg)
    CircleImageView iv_userImg;
    @BindView(R.id.tv_userName)
    TextView tv_userName;
    @BindView(R.id.tv_userComment)
    ExpandTextView tv_userComment;
    @BindView(R.id.tv_commentTime)
    TextView tv_commentTime;
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.ll_collect)
    LinearLayout ll_collect;
    @BindView(R.id.iv_collect)
    ImageView iv_collect;
    @BindView(R.id.tv_collect_status)
    TextView tv_collect_status;
    @BindView(R.id.lay)
    LinearLayout lay;
    @BindView(R.id.ll_have_comment)
    LinearLayout ll_have_comment;
    @BindView(R.id.ll_no_comment)
    LinearLayout ll_no_comment;
    @BindView(R.id.iv_img)
    ImageView iv_img;

    @BindView(R.id.recycler_view)
    RecyclerView recycler_view;
    @BindView(R.id.rv_mass)
    RecyclerView rv_mass;
    @BindView(R.id.gridview)
    NoScrollGridView gridview;
    @BindView(R.id.actionbar)
    TranslucentActionBar actionbar;

    @BindView(R.id.ll_buy)
    LinearLayout ll_buy;
    @BindView(R.id.ll_pin)
    LinearLayout ll_pin;

    @BindView(R.id.tv_oldPrice)
    TextView tv_oldPrice;
    @BindView(R.id.tv_newPrice)
    TextView tv_newPrice;
    @BindView(R.id.tv_look)
    TextView tvLook;
    @BindView(R.id.iv_storeImg)
    ImageView iv_storeImg;
    @BindView(R.id.tv_storeName)
    TextView tv_storeName;
    @BindView(R.id.tv_storeDetail)
    TextView tv_storeDetail;

    private ArrayList<String> imageUrls = new ArrayList<>();
    private boolean isexpand;
    private String token;
    private boolean isCllected = false;

    private String goodsId;
    private String logo_pic;
    private String FromType;
    private List<String> list = new ArrayList<>();
    private ShareDialog shareDialog;
    private String store_id;
    private List<GoodsDetailInfoBean2.InfoBean.BannerBean> bannerlist;
    private GoodsDetailInfoBean2.InfoBean.CommentBean comment;
    private String goodsname;


    public static Intent createIntent(Context context, String goodsId, String logo_pic, String FromType) {
        Intent intent = new Intent(context, RebateGoodsDetailsActivity.class);
        intent.putExtra("goodsId", goodsId);
        intent.putExtra("logo_pic", logo_pic);
        intent.putExtra("FromType", FromType);
        return intent;
    }

    private void parseIntent() {
        Intent intent = getIntent();
        goodsId = intent.getStringExtra("goodsId");
        logo_pic = intent.getStringExtra("logo_pic");
        FromType = intent.getStringExtra("FromType");
    }

    @Override
    protected void handleMsg(Message msg) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_good_detail);
        ButterKnife.bind(this);
        parseIntent();
        actionbar.setData("商品详情", R.drawable.ic_lefft_white, null, R.drawable.ic_xiangqing_share, "分享", 0, this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            actionbar.setStatusBarHeight(getStatusBarHeight());
        }

        if (FromType.equals("1")) {
            lay.setVisibility(View.VISIBLE);
        }
        initView();
        loadData();
    }

    private void loadData() {
        Map<String, String> map = new HashMap<>();
        if (MyApplication.getInstance().getInfoBean() == null){
            MyApplication.getInstance().BackLoginActivity();
            return;
        }
        map.put("token", MyApplication.getInstance().getInfoBean().getToken());
        map.put("goodsId", goodsId);
        map.put("goods_type","2");//1.拼团  2.返利  3.免费
        list.clear();
        OkGo.<String>post(Url.GOODS_DETAILS)
                .tag(this)
                .params(map,false)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("==商品详情-返利==",response.body().toString());
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(response.body());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        String re = jsonObject.optString("re");
                        if (re.equals("1")){
                            Gson gson = new Gson();
                            GoodsDetailInfoBean2 goodsDetailInfoBean = gson.fromJson(response.body(),GoodsDetailInfoBean2.class);
                            goodsId = goodsDetailInfoBean.getInfo().getGoodsId();
                            logo_pic = goodsDetailInfoBean.getInfo().getLogoPic();
                            store_id = goodsDetailInfoBean.getInfo().getStoreId();

                            bannerlist = goodsDetailInfoBean.getInfo().getBanner();
                            comment = goodsDetailInfoBean.getInfo().getComment();
                            for (int i = 0; i < bannerlist.size(); i++) {
                                list.add(bannerlist.get(i).getPic());
                            }
                            initGoodsPic();

                            //评论
                            if ("0".equals(goodsDetailInfoBean.getInfo().getCommentCount())){
                                ll_have_comment.setVisibility(View.GONE);
                                ll_no_comment.setVisibility(View.VISIBLE);
                            }else {
//                                tv_comment_num.setText("("+goodsDetailInfoBean.getInfo().getCommentCount()+")");
                                Glide.with(RebateGoodsDetailsActivity.this).load(comment.getHeadimg()).into(iv_userImg);
                                tv_userName.setText(comment.getNickname());
                                tv_commentTime.setText(comment.getPosttime());
                                Glide.with(RebateGoodsDetailsActivity.this).load(goodsDetailInfoBean.getInfo().getLogoPic()).into(iv_img);
                                /**
                                 * 评论的部分
                                 */
                                tv_userComment.setExpand(isexpand);
                                tv_userComment.setExpandStatusListener(new ExpandTextView.ExpandStatusListener() {
                                    @Override
                                    public void statusChange(boolean isExpand) {
                                        isexpand = isExpand;
                                    }
                                });
                                tv_userComment.setText(comment.getContent());

                                QuanZiImageAdapter ziImageAdapter = new QuanZiImageAdapter(RebateGoodsDetailsActivity.this, comment.getPic());
                                gridview.setAdapter(ziImageAdapter);
                            }


                            //商品
                            goodsname = goodsDetailInfoBean.getInfo().getGoodsName();
                            tv_collect.setText(goodsDetailInfoBean.getInfo().getGoodsName());
                            tv_sales.setText(goodsDetailInfoBean.getInfo().getGoodsTitle());
                            tv_newPrice.setText("¥"+goodsDetailInfoBean.getInfo().getPrice());

                            //店铺
                            Glide.with(RebateGoodsDetailsActivity.this).load(goodsDetailInfoBean.getInfo().getStoreLogo()).into(iv_storeImg);
                            tv_storeName.setText(goodsDetailInfoBean.getInfo().getStoreName());
                            tv_storeDetail.setText("全部商品 "+goodsDetailInfoBean.getInfo().getStoreCount()+"件  已拼团"+0+"次");

                            webView.loadUrl(goodsDetailInfoBean.getInfo().getDetail());
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });

    }

    private void initGoodsPic() {
        /**
         *  商品图
         */
        recycler_view.setLayoutManager(new LinearLayoutManager(RebateGoodsDetailsActivity.this, LinearLayoutManager.HORIZONTAL, false));
        recycler_view.setAdapter(new BaseRVAdapter(RebateGoodsDetailsActivity.this, bannerlist) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_one_item_layout;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                ImageView img = holder.getView(R.id.iv_img);
                Glide.with(RebateGoodsDetailsActivity.this).load(bannerlist.get(position).getPic()).into(img);
            }
        });
    }

    private void initView() {
        ll_collect.setOnClickListener(this);
        ll_buy.setOnClickListener(this);
        ll_pin.setOnClickListener(this);
        tvLook.setOnClickListener(this);
        ll_allComment.setOnClickListener(this);

        //中间画横线
        tv_oldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        /**
         * 商品详情页
         */
        WebSettings webSettings = webView.getSettings();
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        //关闭webview的放大缩小按钮
        webSettings.setDisplayZoomControls(false);
        //设置支持缩放
        webSettings.setBuiltInZoomControls(true);
        webSettings.setLoadWithOverviewMode(false);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);// 排版适应屏幕
        //设置Web视图
        webView.setWebViewClient(new WebClient());
    }

    public class WebClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

        }
    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {
//        //分享
//        ShareInfo shareInfo = new ShareInfo();
//        shareInfo.title = "小鸟云创";
//        shareInfo.text = "专注各种商品商城，优惠多多！";
//        shareInfo.targetUrl = "http://www.baidu.com";
//
//        shareDialog = new ShareDialog(RebateGoodsDetailsActivity.this, shareInfo, null, new UMShareListener() {
//            @Override
//            public void onResult(SHARE_MEDIA platform) {
//                Toast.makeText(RebateGoodsDetailsActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
//                addShareNum();
//            }
//
//            @Override
//            public void onError(SHARE_MEDIA platform, Throwable t) {
//                Toast.makeText(RebateGoodsDetailsActivity.this, "分享失败", Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onCancel(SHARE_MEDIA platform) {
//                Toast.makeText(RebateGoodsDetailsActivity.this, "分享取消", Toast.LENGTH_SHORT).show();
//            }
//        });
//        shareDialog.show();

        //跳转分享页面  (页面标题: 分享商品给好友)
        startActivity(ShareFriandActivity.createIntent(RebateGoodsDetailsActivity.this));

    }

    private void addShareNum() {
        Map<String, String> map = new HashMap<>();
        if (MyApplication.getInstance().getInfoBean() == null){
            MyApplication.getInstance().BackLoginActivity();
            return;
        }
        /**
         @param Str   token
         @param Int   goodsId     商品id
         @param Int   store_id    店铺id
         @param Int   goods_type  1.拼团  2.返利  3.免费
         */
        map.put("token", MyApplication.getInstance().getInfoBean().getToken());
        map.put("goodsId", goodsId);
        map.put("store_id", store_id);
        map.put("goods_type","2");//1.拼团  2.返利  3.免费
        list.clear();
        OkGo.<String>post(Url.GOODS_GOODSSHARE)
                .tag(this)
                .params(map,false)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.e("==商品详情-分享增加次数==",response.body().toString());
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(response.body());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        String re = jsonObject.optString("re");
                        if ("1".equals(re)){
                            LogUtils.e("==商品详情-分享增加次数==","成功");
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });


    }

    @Override
    public void onEditTextClick() {

    }

//    public void setData(GoodsNewBean.InfoBean infoBean) {
//        LogUtils.e("==商品详情==", "进来了3");
//        tv_title.setText(infoBean.getGoods_name());
//
//        tv_price.setText("¥ " + infoBean.getPrice());
//        tv_collect.setText("收藏：" + infoBean.getCollection());
//        tv_sales.setText("月销：" + infoBean.getSales() + "笔");
//        tv_city.setText("地址：" + infoBean.getConsignment());
//
//        weight = infoBean.getWeight();
//        //有无评论的显示
//        if (infoBean.getCommentCount().equals("0")) {
//            ll_no_comment.setVisibility(View.VISIBLE);
//        } else {
//            ll_have_comment.setVisibility(View.VISIBLE);
//
//            tv_comment.setText("宝贝评价(" + infoBean.getCommentCount() + ")");
//            MyImageLoader.displayAvatar(infoBean.getComment().getHeadimg(), iv_userImg);
//            tv_userName.setText(infoBean.getComment().getNickname());
//            String comment = infoBean.getComment().getContent();
//            if (!TextUtils.isEmpty(comment)) {
//                tv_userComment.setExpand(isexpand);
//                tv_userComment.setExpandStatusListener(new ExpandTextView.ExpandStatusListener() {
//                    @Override
//                    public void statusChange(boolean isExpand) {
//                        isexpand = isExpand;
//                    }
//                });
//                tv_userComment.setText(comment);
//            }
//            tv_commentTime.setText(infoBean.getComment().getPosttime());
//
//        }
//
//
//        if (infoBean.getCollect_status().equals("1")) {
//            iv_collect.setBackgroundResource(R.drawable.ic_home_checked);
//            tv_collect_status.setText("已收藏");
//        }
//
//        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
//        webView.getSettings().setLoadWithOverviewMode(false);
//        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);// 排版适应屏幕
//        webView.loadUrl(infoBean.getDetail());
//    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_allComment:
                startActivity(AllCommentActivity.createIntent(RebateGoodsDetailsActivity.this, goodsId,"2"));
                break;
            case R.id.ll_collect:
                collect();
                break;
            case R.id.ll_buy:
                startActivity(AddCartActivity.createIntent(RebateGoodsDetailsActivity.this, goodsId,"" ,logo_pic,""));
                break;
            case R.id.ll_pin:
                startActivity(AddCartActivity.createIntent(RebateGoodsDetailsActivity.this, goodsId,"" ,logo_pic,""));
                break;
            case R.id.tv_look:
                startActivity(StoreActivity.createIntent(this));
                break;
        }
    }

    private void collect() {
        Map<String, Object> map = new HashMap<>();
        if (MyApplication.getInstance().getInfoBean() == null){
            MyApplication.getInstance().BackLoginActivity();
            return;
        }
        /**
         * @param Str    token
         @param int    goodsId     商品id
         @param int    storeId     店铺id
         @param int    type        1-收藏  2-取消收藏
         @param int    goods_type  1.拼团  2.返利  3.免费
         */
        map.put("token", MyApplication.getInstance().getInfoBean().getToken());
        map.put("goodsId", goodsId);
        map.put("storeId", store_id);
        map.put("goods_type", "2");

        if (isCllected) {
            map.put("type", 2);
        } else {
            map.put("type", 1);
        }

        XUtil.Post(Url.GOODS_COLLECT, map, new MyCallBack<String>() {
            @Override
            public void onFinished() {
                super.onFinished();
                if (isCllected) {
                    isCllected = false;
                    iv_collect.setBackgroundResource(R.drawable.ic_home_uncheck);
                    tv_collect_status.setText("收藏");
                } else {
                    isCllected = true;
                    iv_collect.setBackgroundResource(R.drawable.ic_home_checked);
                    tv_collect_status.setText("已收藏");
                }
                ToastUtils.showToast(RebateGoodsDetailsActivity.this, tv_collect_status.getText().toString());
            }

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    LogUtils.e(" ==== 收藏 ==", result);
                    if (jsonObject.optString("re").equals("1")) {
                        if (isCllected) {
                            isCllected = false;
                            iv_collect.setBackgroundResource(R.drawable.ic_home_uncheck);
                            tv_collect_status.setText("收藏");
                            tv_collect.setText("收藏：" + jsonObject.optString("num"));
                        } else {
                            isCllected = true;
                            iv_collect.setBackgroundResource(R.drawable.ic_home_checked);
                            tv_collect_status.setText("已收藏");
                            tv_collect.setText("收藏：" + jsonObject.optString("num"));
                        }
                    }
                    ToastUtils.showToast(RebateGoodsDetailsActivity.this, jsonObject.optString("info"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

}
